<?php
namespace app\admin\controller;

use app\admin\model\Images as ImagesModel;
use think\Validate;

class Images extends Base
{
    public function images_list()
    {
        $list = ImagesModel::order('create_at DESC')->field('id, create_at, images_url, descs')->paginate(15);

        return view('images_list', compact('list'));
    }

    public function images_add()
    {
        return view('images_add');
    }

    public function upload(){

        $file = $this->request->file('file');//file是传文件的名称，这是webloader插件固定写入的。因为webloader插件会写入一个隐藏input，不信你们可以通过浏览器检查页面
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

        // $file = request()->file('pic');

        if ($file) {
            $info = $file->validate(['size'=>15678000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $pathinfo = pathinfo($info->getSaveName());
                $pic = $info->getSaveName();

                $res = ImagesModel::create([
                    'create_at' => time(),
                    'images_url' => $pic,
                ]);

                return success($res, '图片上传成功');
            } else{

                return success($file->getError());
            }
        }
    }

    public function del()
    {
        $id = $this->request->param('id');
        $info = ImagesModel::get($id);
        if($info['images_url']){
            @unlink(ROOT_PATH . 'public' . DS . 'uploads' . DS . $info['images_url']);
        }

        $res = ImagesModel::destroy($id);
        if(!$res){
            return error('删除失败');
        }
        $data['url'] = '/admin/iamges/images_list';

        return success($data, '删除成功');
    }
}
